<template>
  <div id="addStocks">
    <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>业务管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/inStocks' }">物资入库</el-breadcrumb-item>
      <el-breadcrumb-item>添加入库</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->

    <el-row :gutter="20">
      <el-col :span="11">
        <div class="grid-content bg-purple">
          <el-card>
            <el-alert
              title="先勾选右侧表单物资后,再在下方的入库明细中添加入库数量"
              type="info"
              show-icon style="margin-bottom:20px;">
            </el-alert>
            <el-steps style="margin-bottom: 20px;" :active="1" simple>
              <el-step title="填写" icon="el-icon-edit"></el-step>
              <el-step title="审核" icon="el-icon-postcard"></el-step>
              <el-step title="入库" icon="el-icon-set-up"></el-step>
            </el-steps>
            <el-form
              ref="addRuleFormRef"
              :rules="addRules"
              :model="addRuleForm"
              label-width="80px"
            >

              <div>

                <el-form-item label="审核人" prop="auditorId">
                  <el-select v-model="addRuleForm.auditorId" placeholder="请选择审核人">
                    <el-option
                      v-for="auditor in auditors"
                      :key="auditor.id"
                      :label="auditor.username"
                      :value="auditor.id"
                    ></el-option>
                  </el-select>
                </el-form-item>

              </div>

              <el-row>
                <el-col :span="11">
                  <div class="grid-content bg-purple">
                    <el-form-item label="入库明细">
                      <el-button size="mini" plain icon="el-icon-search" @click="drawer = true">明细</el-button>
                    </el-form-item>
                  </div>
                </el-col>

                <el-col :span="11">
                  <div class="grid-content bg-purple">
                    <el-form-item label="商品总类">
                      <el-input-number v-model="itemNum" :disabled="true"></el-input-number>
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>

              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" :rows="2" v-model="addRuleForm.remark"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="add">立即创建</el-button>

                <el-button @click="reset">重置</el-button>
              </el-form-item>
            </el-form>

          </el-card>
        </div>
      </el-col>

      <el-col :span="13">
        <div class="grid-content bg-purple-light">
          <el-card>
            <!-- 查询搜索 -->
            <el-form :inline="true" :model="queryMap" class="demo-form-inline">
              <el-form-item label="分类">
                <el-cascader
                  :change-on-select="true"
                  @change="selectChange"
                  v-model="categorykeys"
                  :props="selectProps"
                  :options="cateories"
                  clearable
                  @clear="search"
                ></el-cascader>
              </el-form-item>
              <el-form-item>
                <el-form-item label="名称">
                  <el-input clearable v-model="queryMap.name" placeholder="名称" @clear="search"></el-input>
                </el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
              </el-form-item>
            </el-form>
            <!-- 入库预选表格 -->
            <el-table
              style="width: 100%"
              max-height="430px"
              :data="tableData"
              :row-key="getRowKey"
              ref="dataTable"
              @selection-change="handleSelectionChange"
              border
            >
              <el-table-column type="selection" :reserve-selection="true"></el-table-column>
              <el-table-column prop="name" label="名称" width="180" fixed="left"></el-table-column>
              <el-table-column prop="model"  label="规格型号" width="100">
                <template slot-scope="scope">
                  <el-tag size="small" effect="plain" type="success">
                    {{ scope.row.model }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="100"></el-table-column>
              <el-table-column prop="remark" label="备注" width="700"></el-table-column>
            </el-table>
            <!-- 表格分页 -->
            <el-pagination
              background
              style="margin-top:10px;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="current"
              :page-sizes="[6, 8, 16, 20]"
              :page-size="size"
              layout="total, sizes, prev, pager, next"
              :total="total"
            ></el-pagination>
            <!-- 抽屉 -->
            <el-drawer size="40%" title="入库明细" :visible.sync="drawer" :with-header="false">
              <span>
                  <el-button size="mini" style="float: right;margin: 10px;" type="primary" icon="el-icon-remove"
                             :disabled="products.length==0" @click="removeAllItem">
                      清空
                  </el-button>
                <el-table height="700" :data="products" border>
                  <el-table-column prop="name" label="名称" width="130px;"></el-table-column>
                  <el-table-column prop="model" label="型号" width="100px;"></el-table-column>
                  <el-table-column label="数量" width="160">
                    <template slot-scope="scope">
                      <el-input-number
                        size="mini"
                        v-model="scope.row.number"
                        :min="0"
                        label="描述文字"
                      ></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unit" label="单位" width="80px;"></el-table-column>
                  <el-table-column label="操作" width="100px;" fixed="right">
                    <template slot-scope="scope">
                      <el-button
                        type="danger"
                        size="mini"
                        plain
                        icon="el-icon-remove"
                        @click="removeItem(scope.row.id)"
                      >移除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </span>
            </el-drawer>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getCatList } from '../../api/category'
import { getGoodsList } from '../../api/goods'
import { getAuditorList } from '../../api/users'
import { add } from '../../api/inStock'

export default {
  data () {
    return {

      supplierInfo: {
        name: '选择后显示具体信息',
        address: '选择后显示地址信息',
        contact: '选择后显示联系人信息',
        phone: '选择后显示联系方式',
        email: '选择后显示邮箱信息'
      },//卡片展示
      provinceList: [], // 省列表
      cityList: [], // 市列表
      originList: [], // 区列表
      cityOptions: [], // 市下拉框数据
      originOptions: [], // 区下拉框数据,
      existence: 0,
      auditors: [],
      cateories: [], //类别选择
      addRules: {
        auditorId: [
          {
            required: true,
            message: '请选择审核人',
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入入库说明备注',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ],
      }, //添加验证
      itemNum: 0,
      addRuleForm: { type: 1 },
      suppliers: [],
      categorykeys: [],
      selectProps: {
        expandTrigger: 'hover',
        value: 'id',
        label: 'name',
        children: 'children'
      }, //级联选择器配置项
      catetorys: [],
      drawer: false,
      current: 1,
      size: 10,
      total: 0,
      queryMap: {
        name: '',
        model: '',
        unit: ''
      },
      tableData: [],
      products: [],
    }
  },
  methods: {
    //重置信息
    reset () {
      this.addRuleForm = { type: 1 }
      this.$refs.addRuleFormRef.clearValidate()
      this.supplierInfo = {
        name: '选择后显示具体信息',
        address: '选择后显示地址信息',
        contact: '选择后显示联系人信息',
        phone: '选择后显示联系方式',
        email: '选择后显示邮箱信息'
      }
    },
    //改变来源选择
    supplerSelectChange (supplierId) {
      const obj = this.suppliers.find(function (x) {
        return x.id === supplierId
      })
      this.supplierInfo = obj
    },
    /**
     * 改变来源
     */
    existenceChange (existence) {
      //选择已经存在的来源
      if (existence === 1) {
      } else if (existence === 0) {
        this.addRuleForm.supplierId = ''
      }
      this.$refs.addRuleFormRef.clearValidate()
      this.supplierInfo = {
        name: '选择后显示具体信息',
        address: '选择后显示地址信息',
        contact: '选择后显示联系人信息',
        phone: '选择后显示联系方式',
        email: '选择后显示邮箱信息'
      }
    },
    /**
     * 创建入库单
     */
    //添加
    add () {
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) {
          return
        } else {
          this.addRuleForm.address =
            this.addRuleForm.province +
            '/' +
            this.addRuleForm.city +
            '/' +
            this.addRuleForm.origin
          const car = []
          try {
            this.products.forEach(row => {

              if (row.number !== undefined && row.number > 0) {
                const item = {productId: row.id, productNumber: row.num};
                car.push(item);
              } else {
                throw Error();
              }
            });
          } catch (err) {
            return this.$message.warning(
              "入库商品的数量不能为空，请勾选物资后在明细中添加数量"
            );
          }
          if (car.length > 0) {
            this.addRuleForm.products = car
          } else {
            return this.$message.warning(
              '入库商品的数量不能为空，请勾选物资后在明细中添加数量'
            )
          }
          const res = await this.$confirm('此操作将提交入库单, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
          if (res === 'confirm') {
            const res = await add(this.addRuleForm)
            if (res.code===200) {
              this.$message.warning('物资入库进入审核状态')
              await this.$router.push('/inStocks')
            } else {
              return this.$message.error('商品入库失败:' + res.message)
            }
          }

          this.addDialogVisible = false
        }
      })
    },
    /**
     * 加载商品列表(可入库)
     */
    async loadTableData () {
      const res = await getGoodsList(this.current, this.size, this.categorys, this.queryMap)
      if (res.code != 200) {
        return this.$message.error('获取商品列表失败')
      } else {
        this.total = res.data.total
        this.tableData = res.data.goodsList
      }
    },
    /**
     * 分类搜索改变时
     */
    selectChange () {
      var str = ''
      for (var i = 0; i < this.categorykeys.length; i++) {
        str += this.categorykeys[i] + ','
      }
      str = str.substring(0, str.length - 1)
      this.categorys = str
    },
    /**
     * 加载商品类别
     */
    async getCatetorys () {
      const res = await getCatList()
      if (res.code != 200) {
        return this.$message.error('获取物资类别失败')
      } else {
        this.cateories = res.data.cat
      }
    },
    /**
     * 加载审核人列表
     */
    async getAuditors () {
      const res = await getAuditorList(4)
      if (res.code != 200) {
        return this.$message.error('获取审核人列表失败')
      } else {
        this.auditors = res.data.auditorsList
      }
    },

    /**
     * 搜索
     */
    search () {
      this.queryMap.pageNum = 1
      this.loadTableData()
    },
    /**
     *  指定一个key标识这一行的数据
     */
    getRowKey (row) {
      return row.id
    },
    /**
     * val表示选中的表格行数据
     */
    handleSelectionChange (val) {
      this.products = val
      this.itemNum = val.length
    },
    /**
     * 改变页码
     */
    handleSizeChange (newSize) {
      this.queryMap.pageSize = newSize
      this.loadTableData()
    },
    /**
     * 点击分页
     */
    handleCurrentChange (current) {
      this.queryMap.pageNum = current
      this.loadTableData()
    },
    /**
     * 清空所有
     */
    removeAllItem () {
      this.products.forEach(row => {
        this.$refs.dataTable.toggleRowSelection(row, false)
      })
      this.products = []
    },

    /**
     * 移除item从抽屉中
     */
    removeItem (val) {
      this.products.forEach(row => {
        if (row.id === val) {
          this.$refs.dataTable.toggleRowSelection(row, false)
        }
      })
      this.products = this.products.filter(item => item.id !== val)
    },
    // 选择省
    changeProvince (val) {
      this.provinceList.forEach((province, index) => {
        if (val.toString() === this.provinceList[index].value) {
          this.cityOptions = this.provinceList[index].children
          this.addRuleForm.valueCity = this.provinceList[
            index
            ].children[0].value //设置市的值
          this.addRuleForm.city = this.provinceList[index].children[0].label

          this.addRuleForm.valueOrigin = this.provinceList[
            index
            ].children[0].children[0].value //设置县的值
          this.addRuleForm.origin = this.provinceList[
            index
            ].children[0].children[0].label

          this.originOptions = this.provinceList[index].children[0].children
          //set value
          this.addRuleForm.province = this.provinceList[index].label
        }
      })
    },
    // 选择市
    changeCity (val) {
      this.cityList.forEach((city, index) => {
        if (val.toString() === this.cityList[index].value) {
          this.originOptions = this.cityList[index].children
          this.addRuleForm.valueOrigin = this.cityList[index].children[0].value //设置县的值;
          //set value
          this.addRuleForm.city = this.cityList[index].label
        }
      })
    },
    // 选择区
    changeOrigin (val) {
      this.addRuleForm.valueOrigin = val

      this.originList.forEach((origin, index) => {
        if (val.toString() === this.originList[index].value) {
          //set value
          this.addRuleForm.origin = this.originList[index].label
        }
      })
      //添加this.$forceUpdate();进行强制渲染，效果实现。搜索资料得出结果：因为数据层次太多，render函数没有自动更新，需手动强制刷新。
      this.$forceUpdate()
    },

    _getJsonData () {
      this.$http.get('/json/provinces.json').then(res => {
        this.provinceList = []
        this.cityList = []
        this.originList = []
        res.data.forEach(item => {
          if (item.value.match(/0000$/)) {
            this.provinceList.push({
              value: item.value,
              label: item.name,
              children: []
            })
          } else if (item.value.match(/00$/)) {
            this.cityList.push({
              value: item.value,
              label: item.name,
              children: []
            })
          } else {
            this.originList.push({
              value: item.value,
              label: item.name
            })
          }
        })
        for (let index in this.provinceList) {
          for (let index1 in this.cityList) {
            if (
              this.provinceList[index].value.slice(0, 2) ===
              this.cityList[index1].value.slice(0, 2)
            ) {
              this.provinceList[index].children.push(this.cityList[index1])
            }
          }
        }
        for (let item1 in this.cityList) {
          for (let item2 in this.originList) {
            if (
              this.originList[item2].value.slice(0, 4) ===
              this.cityList[item1].value.slice(0, 4)
            ) {
              this.cityList[item1].children.push(this.originList[item2])
            }
          }
        }
      })
    }
  },
  created () {
    // this._getJsonData();
    this.loadTableData()
    this.getCatetorys()
    this.getAuditors()
    // this.getSuppliers();
  }
}
</script>
